<template>
  <el-dialog :title="title" v-model="dialogVisible" width="500px" append-to-body @close="handleClose">
    <el-form ref="formRef" :model="formData" :rules="rules" label-width="80px">
      <el-form-item label="分类名称" prop="title">
        <el-input v-model="formData.title" placeholder="请输入分类名称" />
      </el-form-item>
      <el-form-item label="分类排序" prop="sort">
        <el-input-number v-model="formData.sort" :min="1" :max="1000" />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="submitForm(formRef)">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script setup>
import { ref, watch } from 'vue'
import { addEditDecorationCategory, updateDecorationCategory } from '@/api/article'

const props = defineProps({
  title: {
    type: String,
    default: '新增知识分类'
  },
  defaultData: {
    type: Object,
    default: () => null
  },
  dialogShow: {
    type: Boolean,
    required: true,
    default: false
  }
})

const dialogVisible = ref(false)
const formData = ref({
  title: '',
  sort: 1
})

const formRef = ref(null)
const rules = ref({
  title: [
    { required: true, message: '请输入分类名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  sort: [
    { required: true, message: '请输入分类排序', trigger: 'blur' },
    { type: 'number', message: '必须为数字值', trigger: 'blur' }
  ]
})

// 监听对话框显示状态
watch(() => props.dialogShow, (newVal) => {
  dialogVisible.value = newVal
  if (newVal) {
    // 当对话框打开时，如果有默认值则设置表单数据
    if (props.defaultData) {
      formData.value = {
        id: props.defaultData.id,
        title: props.defaultData.title,
        sort: props.defaultData.sort,
      }
    } else {
      // 如果没有默认值，重置表单
      formData.value = {
        title: '',
        sort: 1
      }
    }
  }
})

// 监听默认值变化
watch(() => props.defaultData, (newVal) => {
  console.log(!newVal, 'newVal')
  if (newVal) {
    formData.value = {
      ...formData.value,
      ...newVal
    }
  }
}, { deep: true })

const emit = defineEmits(['update:dialogShow'])

const handleClose = () => {
  dialogVisible.value = false
  emit('update:dialogShow', false)
  // 关闭时重置表单
  formData.value = {
    title: '',
    sort: 1
  }
}

const submitForm = async (formEl) => {
  if (!formEl) return

  await formEl.validate(async (valid, fields) => {
    if (valid) {
      try {
        if (props.defaultData) {
          await updateKnowdgeCategory()
        } else {
          await addKnowdgeCategory()
        }
        dialogVisible.value = false
        emit('update:dialogShow', false)
      } catch (err) {
        console.error(err)
      }
    } else {
      console.error('表单校验失败:', fields)
    }
  })
}

const addKnowdgeCategory = async () => {
  try {
    await addEditDecorationCategory(formData.value)
  } catch (err) {
    console.error(err)
  }
}
const updateKnowdgeCategory = async () => {
  try {
    await updateDecorationCategory(formData.value)
  } catch (err) {
    console.error(err)
  }
}
const cancel = () => {
  handleClose()
}   
</script>